package com.touka.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.touka.common.Result;
import com.touka.entity.*;
import com.touka.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {
  @Autowired
  private OrdersService ordersService;
  @Autowired
  private OrderDetailService orderDetailService;
  @Autowired
  private ShoppingCartService shoppingCartService;
  @Autowired
  private AddressBookService addressBookService;
  @Autowired
  private UserService userService;

  /**
   * 提交订单
   *
   * @param orders
   * @param session
   * @return
   */
  @PostMapping("/submit")
  @Transactional
  public Result<String> pay(@RequestBody Orders orders, HttpSession session) {
    Long userId = (Long) session.getAttribute("user");

    log.info("提交订单：{}-{}", orders, userId);

    // 查询购物车数据
    List<ShoppingCart> shoppingCarts = shoppingCartService.list(
            Wrappers.lambdaQuery(ShoppingCart.class)
                    .eq(ShoppingCart::getUserId, userId)
    );
    // 查询下单地址信息
    AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
    // 查询用户信息
    User user = userService.getById(userId);

    shoppingCarts.forEach(shoppingCart -> {
      BigDecimal amount = orders.getAmount();
      BigDecimal sum = BigDecimal.valueOf(shoppingCart.getNumber()).multiply(shoppingCart.getAmount());
      orders.setAmount(sum.add(amount != null ? amount : new BigDecimal(0)));
    });

    long id = IdWorker.getId();
    orders.setId(id);
    orders.setNumber(String.valueOf(id));
    orders.setUserId(userId);
    orders.setOrderTime(LocalDateTime.now());
    orders.setCheckoutTime(LocalDateTime.now());
    orders.setPhone(addressBook.getPhone());
    orders.setAddress(addressBook.getDetail());
    orders.setUserName(user.getName());
    orders.setConsignee(user.getName());

    ordersService.save(orders);


    List<OrderDetail> orderDetails = shoppingCarts.stream().map(shoppingCart -> {
      OrderDetail orderDetail = new OrderDetail();
      BeanUtils.copyProperties(shoppingCart, orderDetail);
      orderDetail.setOrderId(orders.getId());
      return orderDetail;
    }).toList();

    // 保存订单详情
    orderDetailService.saveBatch(orderDetails);

    //清空购物车数据
    shoppingCartService.remove(Wrappers.lambdaQuery(ShoppingCart.class).eq(ShoppingCart::getUserId, userId));

    return Result.success("提交订单成功");
  }

  /**
   * 分页查询订单数据
   *
   * @param page
   * @param pageSize
   * @param number
   * @param beginTime
   * @param endTime
   * @return
   */
  @GetMapping("/page")
  public Result<Page<Orders>> list(@DefaultValue("1") Long page, @DefaultValue("10") Long pageSize, Long number,
                                   @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime beginTime,
                                   @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
    log.info("获取订单数据：{}-{}-{}-{}-{}", page, pageSize, number, beginTime, endTime);
    Page<Orders> pageOrders = new Page<>(page, pageSize);
    Page<Orders> ordersPage = ordersService.page(pageOrders, Wrappers.lambdaQuery(Orders.class)
            .eq(number != null, Orders::getNumber, number)
            .between(beginTime != null && endTime != null, Orders::getOrderTime, beginTime, endTime)
    );

    return Result.success(ordersPage);
  }

  /**
   * 查询当前用户订单信息
   *
   * @param page
   * @param pageSize
   * @param session
   * @return
   */
  @GetMapping("/userPage")
  public Result<Page<Orders>> userPage(@DefaultValue("1") Long page, @DefaultValue("10") Long pageSize, HttpSession session) {
    log.info("查询用户订单：{}-{}", page, pageSize);
    Page<Orders> ordersPage = new Page<>(page, pageSize);
    Page<Orders> pageOrders = ordersService.page(ordersPage, Wrappers.lambdaQuery(Orders.class).eq(Orders::getUserId, session.getAttribute("user")));
    return Result.success(pageOrders);
  }
}
